<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,">










<meta name="description" content="1.ThreadLocal 是什么？ThreadLocal 是一个本地线程副本变量工具类。主要用于将私有线程和该线程存放的副本对象做一个映射，各个线程之间的变量互不干扰，在高并发场景下，可以实现无状态的调用，适用于各个线程不共享变量值的操作。 2.ThreadLocal 工作原理是什么？ThreadLocal 原理：每个线程的内部都维护了一个 ThreadLocalMap，它是一个 Map（key">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="ThreadLocal详解">
<meta property="og:url" content="https://blog.xiezc.xyz/2019/03/07/java常用类解析/TreadLocal类/index.html">
<meta property="og:site_name" content="xiezc的小站">
<meta property="og:description" content="1.ThreadLocal 是什么？ThreadLocal 是一个本地线程副本变量工具类。主要用于将私有线程和该线程存放的副本对象做一个映射，各个线程之间的变量互不干扰，在高并发场景下，可以实现无状态的调用，适用于各个线程不共享变量值的操作。 2.ThreadLocal 工作原理是什么？ThreadLocal 原理：每个线程的内部都维护了一个 ThreadLocalMap，它是一个 Map（key">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/3/7/169556d3bce81fef?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https:////upload-images.jianshu.io/upload_images/2615789-bf2dfb86819f6823.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/208/format/webp">
<meta property="og:image" content="https:////upload-images.jianshu.io/upload_images/2615789-32b422909f2f933c.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/696/format/webp">
<meta property="og:image" content="https:////upload-images.jianshu.io/upload_images/2615789-0d85565e94c4bd6b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/722/format/webp">
<meta property="og:updated_time" content="2019-04-04T14:26:28.142Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ThreadLocal详解">
<meta name="twitter:description" content="1.ThreadLocal 是什么？ThreadLocal 是一个本地线程副本变量工具类。主要用于将私有线程和该线程存放的副本对象做一个映射，各个线程之间的变量互不干扰，在高并发场景下，可以实现无状态的调用，适用于各个线程不共享变量值的操作。 2.ThreadLocal 工作原理是什么？ThreadLocal 原理：每个线程的内部都维护了一个 ThreadLocalMap，它是一个 Map（key">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2019/3/7/169556d3bce81fef?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.xiezc.xyz/2019/03/07/java常用类解析/TreadLocal类/">





  <title>ThreadLocal详解 | xiezc的小站</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8ae02d8cf311eabbae2621ff2d51a260";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xiezc的小站</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">xiezc的小站</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.xiezc.xyz/2019/03/07/java常用类解析/TreadLocal类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xiezc">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xiezc的小站">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ThreadLocal详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-07T17:31:40+08:00">
                2019-03-07
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/03/07/java常用类解析/TreadLocal类/" class="leancloud_visitors" data-flag-title="ThreadLocal详解">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="1-ThreadLocal-是什么？"><a href="#1-ThreadLocal-是什么？" class="headerlink" title="1.ThreadLocal 是什么？"></a>1.ThreadLocal 是什么？</h4><p>ThreadLocal 是一个本地线程副本变量工具类。主要用于将私有线程和该线程存放的副本对象做一个映射，各个线程之间的变量互不干扰，在高并发场景下，可以实现无状态的调用，适用于各个线程不共享变量值的操作。</p>
<h4 id="2-ThreadLocal-工作原理是什么？"><a href="#2-ThreadLocal-工作原理是什么？" class="headerlink" title="2.ThreadLocal 工作原理是什么？"></a>2.ThreadLocal 工作原理是什么？</h4><p>ThreadLocal 原理：每个线程的内部都维护了一个 ThreadLocalMap，它是一个 Map（key,value）数据格式，key 是一个弱引用，也就是 ThreadLocal 本身，而 value 存的是线程变量的值。</p>
<blockquote>
<p>弱引用, WeakReference当一个对象只用弱引用的时候, 收集器发现它了就会回收它, 没发现就是还可以使用的</p>
<p>软引用,   SoftReference 当内存不足的时候, 在进行fullGC之前会回收软引用, 所以使用用来作为缓存</p>
<p>虚引用 PhantomReference 这个引用丝毫不会影响它的回收,虚引用主要用来跟踪对象被垃圾回收器回收的活动</p>
</blockquote>
<p>也就是说 ThreadLocal 本身并不存储线程的变量值，它只是一个工具，用来维护线程内部的 Map，帮助存和取变量。</p>
<blockquote>
<p>这个类的结构类似, Map&lt;线程ID, Map&lt;ThreadLocal对象,value&gt;&gt; 的线程安全的静态类 </p>
</blockquote>
<p>数据结构，如下图所示：</p>
<p><img src="https://user-gold-cdn.xitu.io/2019/3/7/169556d3bce81fef?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<p><em>（图片来源于网络）</em></p>
<h4 id="3-ThreadLocal-如何解决-Hash-冲突？"><a href="#3-ThreadLocal-如何解决-Hash-冲突？" class="headerlink" title="3.ThreadLocal 如何解决 Hash 冲突？"></a>3.ThreadLocal 如何解决 Hash 冲突？</h4><blockquote>
<p>ThreadLocalMap 是当前线程对象thread中成员变量, 当set数据的时候, 会获得这个成员变量, 如果获得的是空的就会new一个, </p>
</blockquote>
<p>与 HashMap 不同，ThreadLocalMap 结构非常简单，没有 next 引用，也就是说 ThreadLocalMap 中解决 Hash 冲突的方式并非链表的方式，而是采用线性探测的方式。所谓线性探测，就是根据初始 key 的 hashcode 值确定元素在 table 数组中的位置，如果发现这个位置上已经被其他的 key 值占用，则利用固定的算法寻找一定步长的下个位置，依次判断，直至找到能够存放的位置。</p>
<blockquote>
<p>ThreadLocal的key 是new的这个对象本身, 且是弱引用. </p>
</blockquote>
<p>源代码实现如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">/</span><br><span class="line"> * Increment i modulo len.</span><br><span class="line"> */</span><br><span class="line">private static int nextIndex(int i, int len) &#123;</span><br><span class="line">    return ((i + 1 &lt; len) ? i + 1 : 0);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/</span><br><span class="line"> * Decrement i modulo len.</span><br><span class="line"> */</span><br><span class="line">private static int prevIndex(int i, int len) &#123;</span><br><span class="line">    return ((i - 1 &gt;= 0) ? i - 1 : len - 1);</span><br><span class="line">&#125;</span><br><span class="line">复制代码</span><br></pre></td></tr></table></figure>
<h4 id="4-ThreadLocal-的内存泄露是怎么回事？"><a href="#4-ThreadLocal-的内存泄露是怎么回事？" class="headerlink" title="4.ThreadLocal 的内存泄露是怎么回事？"></a>4.ThreadLocal 的内存泄露是怎么回事？</h4><p>ThreadLocal 在 ThreadLocalMap 中是以一个弱引用身份被 Entry 中的 Key 引用的，因此如果 ThreadLocal 没有外部强引用来引用它，那么 ThreadLocal 会在下次 JVM 垃圾收集时被回收。这个时候 Entry 中的 key 已经被回收，但是 value 又是一强引用不会被垃圾收集器回收，这样 ThreadLocal 的线程如果一直持续运行，value 就一直得不到回收，这样就会发生内存泄露。</p>
<h4 id="5-为什么-ThreadLocalMap-的-key-是弱引用？"><a href="#5-为什么-ThreadLocalMap-的-key-是弱引用？" class="headerlink" title="5.为什么 ThreadLocalMap 的 key 是弱引用？"></a>5.为什么 ThreadLocalMap 的 key 是弱引用？</h4><blockquote>
<p>使用弱引用确实很巧妙, 但是使用不当还是会出现内存泄漏的</p>
<p>意的是<strong>Entry中的key是弱引用，当threadLocal外部强引用被置为null(threadLocalInstance=null),那么系统 GC 的时候，根据可达性分析，这个threadLocal实例就没有任何一条链路能够引用到它，这个ThreadLocal势必会被回收，这样一来，ThreadLocalMap中就会出现key为null的Entry，就没有办法访问这些key为null的Entry的value，如果当前线程再迟迟不结束的话，这些key为null的Entry的value就会一直存在一条强引用链：Thread Ref -&gt; Thread -&gt; ThreaLocalMap -&gt; Entry -&gt; value永远无法回收，造成内存泄漏。</strong>当然，如果当前thread运行结束，threadLocal，threadLocalMap,Entry没有引用链可达，在垃圾回收的时候都会被系统进行回收。在实际开发中，会使用线程池去维护线程的创建和复用，比如固定大小的线程池，线程为了复用是不会主动结束的，所以，threadLocal的内存泄漏问题，是应该值得我们思考和注意的问题，关于这个问题可以看这篇文章—-<a href="https://www.jianshu.com/p/dde92ec37bd1" target="_blank" rel="noopener">详解threadLocal内存泄漏问题</a></p>
</blockquote>
<p>我们知道 ThreadLocalMap 中的 key 是弱引用，而 value 是强引用才会导致内存泄露的问题，至于为什么要这样设计，这样分为两种情况来讨论：</p>
<ul>
<li>key 使用强引用：这样会导致一个问题，引用的 ThreadLocal 的对象被回收了，但是 ThreadLocalMap 还持有 ThreadLocal 的强引用，如果没有手动删除，ThreadLocal 不会被回收，则会导致内存泄漏。</li>
<li>key 使用弱引用：这样的话，引用的 ThreadLocal 的对象被回收了，由于 ThreadLocalMap 持有 ThreadLocal 的弱引用，即使没有手动删除，ThreadLocal 也会被回收。<em>value 在下一次 ThreadLocalMap 调用 set、get、remove 的时候会被清除</em>。</li>
</ul>
<p>比较以上两种情况，我们可以发现：由于 ThreadLocalMap 的生命周期跟 Thread 一样长，如果都没有手动删除对应 key，都会导致内存泄漏，但是使用弱引用可以多一层保障，弱引用 ThreadLocal 不会内存泄漏，对应的 value 在下一次 ThreadLocalMap 调用 set、get、remove 的时候被清除，算是最优的解决方案。</p>
<h4 id="6-ThreadLocal-的应用场景有哪些？"><a href="#6-ThreadLocal-的应用场景有哪些？" class="headerlink" title="6.ThreadLocal 的应用场景有哪些？"></a>6.ThreadLocal 的应用场景有哪些？</h4><blockquote>
<p>mybatis的与spring的结合就是使用的ThreadLocal.  会将数据库连接放入ThreadLoacl中, 当运行某个查询方法的时候, 在AOP的before中获得连接, 并且根据情况开启事务, 在最后after的时候commit连接,  这样用户就可以实现无感知的”不调用”的jdbc来达到操作数据库的目的</p>
</blockquote>
<p>ThreadLocal 适用于独立变量副本的情况，比如 Hibernate 的 session 获取场景。</p>
<p>示例代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">private static final ThreadLocal&lt;Session&gt; threadLocal = new ThreadLocal&lt;Session&gt;();</span><br><span class="line"></span><br><span class="line">public static Session getCurrentSession()&#123;</span><br><span class="line">    Session session =  threadLocal.get();</span><br><span class="line">    try &#123;</span><br><span class="line">        if(session ==null&amp;&amp;!session.isOpen())&#123;</span><br><span class="line">            //...</span><br><span class="line">        &#125;</span><br><span class="line">        threadLocal.set(session);</span><br><span class="line">    &#125; catch (Exception e) &#123;</span><br><span class="line">        // TODO: handle exception</span><br><span class="line">    &#125;</span><br><span class="line">    return session;</span><br><span class="line">&#125;</span><br><span class="line">复制代码</span><br></pre></td></tr></table></figure>
<h2 id="set方法"><a href="#set方法" class="headerlink" title="set方法"></a>set方法</h2><p>与concurrentHashMap，hashMap等容器一样，threadLocalMap也是采用散列表进行实现的。在了解set方法前，我们先来回顾下关于散列表相关的知识（摘自<a href="https://www.cnblogs.com/zhangjk1993/archive/2017/03/29/6641745.html" target="_blank" rel="noopener">这篇的threadLocalMap的讲解部分</a>以及<a href="http://faculty.cs.niu.edu/~freedman/340/340notes/340hash.htm" target="_blank" rel="noopener">这篇文章的hash</a>）。</p>
<ul>
<li>散列表</li>
</ul>
<p> 理想状态下，散列表就是一个包含关键字的固定大小的数组，通过使用散列函数，将关键字映射到数组的不同位置。下面是</p>
<p><img src="https:////upload-images.jianshu.io/upload_images/2615789-bf2dfb86819f6823.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/208/format/webp" alt="img"></p>
<p>理想散列表的一个示意图</p>
<p>在理想状态下，哈希函数可以将关键字均匀的分散到数组的不同位置，不会出现两个关键字散列值相同（假设关键字数量小于数组的大小）的情况。但是在实际使用中，经常会出现多个关键字散列值相同的情况（被映射到数组的同一个位置），我们将这种情况称为散列冲突。为了解决散列冲突，主要采用下面两种方式： <strong>分离链表法</strong>（separate chaining）和<strong>开放定址法</strong>（open addressing）</p>
<ul>
<li>分离链表法</li>
</ul>
<p>分散链表法使用链表解决冲突，将散列值相同的元素都保存到一个链表中。当查询的时候，首先找到元素所在的链表，然后遍历链表查找对应的元素，典型实现为hashMap，concurrentHashMap的拉链法。下面是一个示意图：</p>
<p><img src="https:////upload-images.jianshu.io/upload_images/2615789-32b422909f2f933c.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/696/format/webp" alt="img"></p>
<p>分离链表法示意图</p>
<p>图片来自 <a href="http://faculty.cs.niu.edu/~freedman/340/340notes/340hash.htm" target="_blank" rel="noopener">http://faculty.cs.niu.edu/~freedman/340/340notes/340hash.htm</a></p>
<ul>
<li>开放定址法</li>
</ul>
<p>开放定址法不会创建链表，当关键字散列到的数组单元已经被另外一个关键字占用的时候，就会尝试在数组中寻找其他的单元，直到找到一个空的单元。探测数组空单元的方式有很多，这里介绍一种最简单的 – 线性探测法。线性探测法就是从冲突的数组单元开始，依次往后搜索空单元，如果到数组尾部，再从头开始搜索（环形查找）。如下图所示：</p>
<p><img src="https:////upload-images.jianshu.io/upload_images/2615789-0d85565e94c4bd6b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/722/format/webp" alt="img"></p>
<p>开放定址法示意图</p>
<p>图片来自 <a href="http://alexyyek.github.io/2014/12/14/hashCollapse/" target="_blank" rel="noopener">http://alexyyek.github.io/2014/12/14/hashCollapse/</a></p>
<p>关于两种方式的比较，可以参考 <a href="http://www.nowamagic.net/academy/detail/3008060" target="_blank" rel="noopener">这篇文章</a>。<strong>ThreadLocalMap 中使用开放地址法来处理散列冲突</strong>，而 HashMap 中使用的分离链表法。之所以采用不同的方式主要是因为：在 ThreadLocalMap 中的散列值分散的十分均匀，很少会出现冲突。并且 ThreadLocalMap 经常需要清除无用的对象，使用纯数组更加方便。</p>
<p>在了解这些相关知识后我们再回过头来看一下set方法。set方法的源码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">private void set(ThreadLocal&lt;?&gt; key, Object value) &#123;</span><br><span class="line"></span><br><span class="line">    // We don&apos;t use a fast path as with get() because it is at</span><br><span class="line">    // least as common to use set() to create new entries as</span><br><span class="line">    // it is to replace existing ones, in which case, a fast</span><br><span class="line">    // path would fail more often than not.</span><br><span class="line"></span><br><span class="line">    Entry[] tab = table;</span><br><span class="line">    int len = tab.length;</span><br><span class="line">    //根据threadLocal的hashCode确定Entry应该存放的位置</span><br><span class="line">    int i = key.threadLocalHashCode &amp; (len-1);</span><br><span class="line"></span><br><span class="line">    //采用开放地址法，hash冲突的时候使用线性探测</span><br><span class="line">    for (Entry e = tab[i];</span><br><span class="line">         e != null;</span><br><span class="line">         e = tab[i = nextIndex(i, len)]) &#123;</span><br><span class="line">        ThreadLocal&lt;?&gt; k = e.get();</span><br><span class="line">        //覆盖旧Entry</span><br><span class="line">        if (k == key) &#123;</span><br><span class="line">            e.value = value;</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        //当key为null时，说明threadLocal强引用已经被释放掉，那么就无法</span><br><span class="line">        //再通过这个key获取threadLocalMap中对应的entry，这里就存在内存泄漏的可能性</span><br><span class="line">        if (k == null) &#123;</span><br><span class="line">            //用当前插入的值替换掉这个key为null的“脏”entry</span><br><span class="line">            replaceStaleEntry(key, value, i);</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    //新建entry并插入table中i处</span><br><span class="line">    tab[i] = new Entry(key, value);</span><br><span class="line">    int sz = ++size;</span><br><span class="line">    //插入后再次清除一些key为null的“脏”entry,如果大于阈值就需要扩容</span><br><span class="line">    if (!cleanSomeSlots(i, sz) &amp;&amp; sz &gt;= threshold)</span><br><span class="line">        rehash();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>作者：你听___</p>
<p>链接：<a href="https://www.jianshu.com/p/30ee77732843" target="_blank" rel="noopener">https://www.jianshu.com/p/30ee77732843</a></p>
<p>来源：简书</p>
<p>简书著作权归作者所有，任何形式的转载都请联系作者获得授权并注明出处。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/19/异步同步 阻塞非阻塞/" rel="next" title>
                <i class="fa fa-chevron-left"></i> 
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/07/java的四种引用理解/" rel="prev" title="java的四种引用理解">
                java的四种引用理解 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">xiezc</p>
              <p class="site-description motion-element" itemprop="description">主要一些技术文章, 有些文章是转载的</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">72</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-ThreadLocal-是什么？"><span class="nav-number">1.</span> <span class="nav-text">1.ThreadLocal 是什么？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-ThreadLocal-工作原理是什么？"><span class="nav-number">2.</span> <span class="nav-text">2.ThreadLocal 工作原理是什么？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-ThreadLocal-如何解决-Hash-冲突？"><span class="nav-number">3.</span> <span class="nav-text">3.ThreadLocal 如何解决 Hash 冲突？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-ThreadLocal-的内存泄露是怎么回事？"><span class="nav-number">4.</span> <span class="nav-text">4.ThreadLocal 的内存泄露是怎么回事？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-为什么-ThreadLocalMap-的-key-是弱引用？"><span class="nav-number">5.</span> <span class="nav-text">5.为什么 ThreadLocalMap 的 key 是弱引用？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-ThreadLocal-的应用场景有哪些？"><span class="nav-number">6.</span> <span class="nav-text">6.ThreadLocal 的应用场景有哪些？</span></a></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#set方法"><span class="nav-number"></span> <span class="nav-text">set方法</span></a></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xiezc</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("eRAHvO0xVYwckgdXIVpfugRG-gzGzoHsz", "57lKp708hde92YeG1xX9MQj1");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
